// 导入用户集合
const { User } = require('../../model/user');
const { RoleType } = require('../../model/roleType');
const { generateToken } =  require('../../middleGuard/jwt.js')

module.exports = async (req, res) => {
  const body = req.body
  console.log('body', body)
  const user = await User.findOne({
    username: body.username
  })
  if (!user) {
      res.status(403)
      res.json({
          message: '用户不存在！'
      })
  } else {
      if(user.password === body.password) {
        if (user.state !== 0) {
          const { username, email, roleType, _id, avatar } = user
          const role = await RoleType.findOne({
            value: roleType
          })
          const data = {
              _id,
              username,
              email, 
              roleType,
              role,
              avatar
          }
          const token = generateToken({userId: _id})
          data.token = token
          res.json({
              data,
              message: '登录成功！'
          })
        } else {
          res.status(403)
          res.json({
              message: '用户已被冻结！'
          })
        }
      } else {
          res.status(403)
          res.json({
              message: '密码错误！'
          })
      }
  }
  console.log(user)
}